<?php
/**
 * Tên file mình có thể tự chọn nhưng nên đặc theo têm controller sẽ dễ quản lý
 */

/**
 * Tên class: Example_Models_Dao_Pdo_Mysql_Example(Tenmodule_Models_Dao_Pdo_Mysql_Tenfile)
 */

class Enterprise_Models_Dao_Pdo_Mysql_User extends Tomato_Model_Dao
    implements Enterprise_Models_Interface_User
{
    public function convert($entity)
    {
        return new Enterprise_Models_User($entity);
    }

    public function getRoleByName($name){
        $row = $this->_conn
                    ->select()
                    ->from(array('r' => $this->_prefix . 'core_role'))
                    ->where('r.name = ?', $name)
                    ->limit(1)
                    ->query()
                    ->fetch();
        return (null == $row) ? null : new Core_Models_Role($row);
    }

    public function add($user){
        $this->_conn->insert($this->_prefix . 'enterprise_user_accounts',
                            array(
                                'enterprise_id' => $user->enterprise_id,
                                'user_id'    => $user->user_id,
                            ));
        return $this->_conn->lastInsertId($this->_prefix . 'enterprise_user_accounts');
    }

    public function getById($id){
        $rs = $this->_conn
                    ->select()
                    ->from(array('uc' => $this->_prefix . 'enterprise_user_accounts'))
                    ->where('uc.enterprise_id = ?', $id)
                    ->query()
                    ->fetchAll();
        return new Tomato_Model_RecordSet($rs, $this);
    }

    public function getUserAccountBy($enterprise_id){
        $rs = $this->_conn
                    ->select()
                    ->from(array('uc' => $this->_prefix . 'enterprise_user_accounts'),array('enterprise_id'))
                    ->joinInner(array('u' => $this->_prefix . 'core_user'), 'u.user_id = uc.user_id')
                    ->joinInner(array('r' => $this->_prefix . 'core_role'), 'r.role_id = u.role_id', array('role_name' => 'name'))
                    ->where('uc.enterprise_id = ?', $enterprise_id)
                    ->query()
                    ->fetchAll();
        return new Tomato_Model_RecordSet($rs, $this);
    }

    public function getByUser($user_id){
        $row = $this->_conn
                    ->select()
                    ->from(array('uc' => $this->_prefix . 'enterprise_user_accounts'))
                    ->where('uc.user_id = ?', $user_id)
                    ->limit(1)
                    ->query()
                    ->fetch();
        return (null == $row) ? null : new Enterprise_Models_User($row);
    }
}
